<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>组件vModel</title>
  <script src="https://unpkg.com/vue@2"></script>
</head>
<body>
  <div id="app">
    <!-- custom-input组件使用vModel -->
    <div class="wrap">
      <h5 class="title">custom-input组件使用vModel</h5>
      <custom-input v-model="searchText"></custom-input>
      <p class="preview">绑定值为: {{ searchText }}</p>
    </div>

    <!-- custom-checkbox组件使用v-model -->
    <div class="wrap">
      <h5 class="title">custom-checkbox组件使用vModel</h5>
      <custom-checkbox v-model="checkText"></custom-checkbox>已选择
      <p class="preview">绑定值为: {{ checkText }}</p>
    </div>
  </div>
</body>
<style>
  .wrap {
    background: #f3f3f3;
    padding: 10px;
    margin-bottom: 16px;
  }
  .wrap .title {
    margin: 0;
    margin-bottom: 20px;
    border-bottom: 1px solid #ddd;
    line-height: 2;
    font-size: 14px;
  }
  .wrap .preview {
    font-size: 13px;
  }
</style>
<script>
  // 自定义custom-input使用v-model
  
  /**
   * 注意: 关于$event:
   * el-input组件 value = $event
   * input原生标签 value = $event.targte.value
  */
  Vue.component('custom-input', {
    props: ['value'],
    template: `
      <input type="text" 
        :value="value" 
        @input="$emit('input', $event.target.value)" 
      />
    `,
  })

  // 自定义custom-checkbox使用v-model
  Vue.component('custom-checkbox', {
    model: {
      prop: 'checked', // 定义prop字段名
      event: 'change', // 定义event字段名
    },
    props: ['checked'],
    template: `
      <input 
        type="checkbox" 
        :checked="checked" 
        @change="$emit('change', $event.target.checked)"
      />
    `,
  })

  var app = new Vue({
    el: '#app',
    data: {
      searchText: '',
      checkText: false,
    }
  })
</script>
</html>
